﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Drawing;
using System.Xml;

namespace VideoCoreWCF {
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple,
        InstanceContextMode = InstanceContextMode.PerSession,
        UseSynchronizationContext = true)]
    public class VideoCore : IVideoCore {
        private string m_camerasFile = @"D:\Cameras.xml";
        // cameras
        public readonly CameraCollection m_cameras = new CameraCollection();
        public IList<IPCamera> GetCameraList() {
            //Read IP camera list from local server XML file
            XmlDocument doc = new XmlDocument();
            doc.Load(m_camerasFile);
            XmlNode root = doc.SelectSingleNode("//Cameras");
            if (root != null)
            {
                List<IPCamera> results = new List<IPCamera>(root.ChildNodes.Count);
                foreach (XmlNode node in root.ChildNodes)
                {
                    Guid id = new Guid(node.Attributes["id"].Value);
                    string user = node.Attributes["user"].Value;
                    string pwd = node.Attributes["password"].Value;
                    string ip = node.Attributes["ip"].Value;
                    string name = node.Attributes["name"].Value;
                    bool onOff = Boolean.Parse(node.Attributes["onoff"].Value);
                    bool available = Boolean.Parse(node.Attributes["available"].Value);
                    results.Add(new IPCamera { ID = id, Name = name, UserName = user, Password = pwd, IPAddress = ip, OnOff = onOff, Available = available });
                }
                return results;
            }
            return new List<IPCamera>();
        }
        public bool SaveIPCamera(IPCamera vIPCamera) {
            // Add/Update IPCamera to local server XML file
            m_cameras.Add(vIPCamera);

            XmlDocument doc = new XmlDocument();

            if (File.Exists(m_camerasFile))
            {
                doc.Load(m_camerasFile);
            }
            XmlNode root = doc.SelectSingleNode("//Cameras");
            if (root == null)
            {
                root = doc.CreateElement("Cameras");
                doc.AppendChild(root);
            }
            foreach (IPCamera camera in m_cameras)
            {
                // new "Camera" node
                XmlElement elem = doc.CreateElement("Camera");
                // writer.WriteStartElement("Camera");
                elem.SetAttribute("id", camera.ID.ToString());
                elem.SetAttribute("name", camera.Name);
                elem.SetAttribute("ip", camera.IPAddress);
                elem.SetAttribute("user", camera.UserName);
                elem.SetAttribute("password", camera.Password);
                elem.SetAttribute("onoff", camera.OnOff.ToString());
                elem.SetAttribute("available", camera.Available.ToString());
                root.AppendChild(elem);
                doc.Save(m_camerasFile);
            }
            return true;
        }
        public bool DeleteIPCamera(IPCamera vIPCamera) {
            // Delete IPCamera from local server XML file
            return true;
        }
        public string CreateCameraStream(IPCameraCommand vCommand) {
            // Create HTTP or RTSP stream from the camera. The return value is the new URL that the Media Element should connect to.
            return "http(or RTSP)://localhost/VideoStream" + Guid.NewGuid().ToString();
        }
        public byte[] GetVideoStream(string fileName, long frame) {
            return VideoCacheProvider.Current.GetFrame(fileName, frame);
        }
        public string Welcome() {
            return "Connect to server successful!";
        }

        #region IVideoCore Members


        /// <summary>
        /// Gets the next file.
        /// </summary>
        /// <param name="currentFileName">Name of the current file.</param>
        /// <returns></returns>
        public VideoFileInfo GetNextFile(string IP, string currentFileName) {
            string fileName = FileHelper.GetNextFile(IP, currentFileName);
            return VideoCacheProvider.Current.GetFileInfo(fileName);
        }

        /// <summary>
        /// Gets the last file.
        /// </summary>
        /// <returns></returns>
        public VideoFileInfo GetLastFile(string IP) {
            string shortFileName = FileHelper.GetFile(IP, DateTime.Now, true);
            return VideoCacheProvider.Current.GetFileInfo(shortFileName);
        }

        #endregion

        #region IVideoCore Members


        /// <summary>
        /// Gets the date at.
        /// </summary>
        /// <param name="IP">The IP.</param>
        /// <param name="dateTime">The date time.</param>
        /// <returns></returns>
        public VideoFileInfo GetDateAt(string IP, DateTime dateTime) {
            string shortFileName = FileHelper.GetFile(IP, dateTime, false);
            return VideoCacheProvider.Current.GetFileInfo(shortFileName);
        }

        #endregion
    }

}
